package render

import (
    "html/template"
    "net/http"
)

var (
    htmlContentType = "text/html; charset=utf-8"
)

type HtmlRender interface {
    Instance(name string, data interface{}) Render
}

type HTMLProduction struct {
    Files       []string
    Glob        string
    FuncMap     map[string]interface{}
    template    *template.Template
    isReload    bool
}

type Html struct {
    Template    *template.Template
    Name        string
    Data        interface{}
}

func (this *HTMLProduction) Instance(name string, data interface{}) Render {
    if this.isReload {
        this.reloadTemplate()
    }
    return &Html{
        Template:   this.template,
        Name:       name,
        Data:       data,
    }
}

func (this *HTMLProduction) reloadTemplate() {
    t := template.New("")
    t.Funcs(template.FuncMap(this.FuncMap))
    if len(this.Files) > 0 {
        t = template.Must(t.ParseFiles(this.Files...))
    }
    if this.Glob != "" {
        t = template.Must(t.ParseGlob(this.Glob))
    }
    this.template = t
}

func (this *Html) Render(w http.ResponseWriter, headerCode int) error {
    setContentType(w, htmlContentType)
    w.WriteHeader(headerCode)
    if this.Name == "" {
        return this.Template.Execute(w, this.Data)
    } else {
        return this.Template.ExecuteTemplate(w, this.Name, this.Data)
    }
}

func NewHTMLProduction(files []string, glob string, funcMap map[string]interface{}, isReload bool) *HTMLProduction {
    h := &HTMLProduction{
        Files:      files,
        Glob:       glob,
        FuncMap:    funcMap,
        isReload:   isReload,
    }
    h.reloadTemplate()
    return h
}
